package cn.geoportal.benoserver.controller;

import cn.geoportal.benoserver.config.RabbitMqConfig;
import cn.geoportal.benoserver.entity.ShploadTask;
import cn.geoportal.benoserver.entity.Spatialdb;
import cn.geoportal.benoserver.entity.common.PageResult;
import cn.geoportal.benoserver.entity.common.RespBean;
import cn.geoportal.benoserver.entity.vo.shpload.ShploadAdd;
import cn.geoportal.benoserver.entity.vo.shpload.ShploadGet;
import cn.geoportal.benoserver.service.ShploadTaskService;
import cn.geoportal.benoserver.service.SpatialdbService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: chiangbt@geoportal.cn
 * @CreatedAt: 2021/10/13 11:17 上午
 **/
@Api(tags = "2.Shp数据导入")
@ApiSupport(order = 303)
@RestController
@RequestMapping("/api/shploadtask")
public class ShploadTaskController {

    @Autowired
    private ShploadTaskService shploadTaskService;
    @Autowired
    private SpatialdbService spatialdbService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${toolpath.pgtool}")
    private String pgtool;

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "ShpLoad列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "当前页号", required = true, example = "1"),
            @ApiImplicitParam(name = "pageSize", value = "批次数量", required = true, example = "15"),
            @ApiImplicitParam(name = "query", value = "名称", required = false, example = ""),
            @ApiImplicitParam(name = "type", value = "转换类型", required = false, example = "")
    })
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public RespBean list(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                         @RequestParam(value = "pageSize", defaultValue = "3") Integer pageSize,
                         @RequestParam(value = "query", defaultValue = "") String query,
                         @RequestParam(value = "type", defaultValue = "-1") Integer type) {
        QueryWrapper<ShploadTask> wrapper = new QueryWrapper<>();
        if (type == -1) {
            System.out.println("a");
            wrapper.like("a.name", query.toLowerCase()).or().like("a.name", query.toUpperCase())
                    .or().like("a.description", query.toLowerCase()).or().like("a.description", query.toUpperCase());
        } else {
            System.out.println("b");
            wrapper.eq("a.dbid", type).and(Wrapper -> Wrapper.like("a.name", query.toLowerCase()).or().like("a.name", query.toUpperCase())
                    .or().like("a.description", query.toLowerCase()).or().like("a.description", query.toUpperCase()));
        }
        Page<ShploadTask> ipage = new Page<>(pageNo, pageSize);
        try {
            IPage<ShploadTask> dt = shploadTaskService.queryShploadPage(ipage, wrapper);
            dt.getRecords().forEach(e -> {
                String status = e.getStatus();
                if("0".equals(status)){
                    e.setStatusName("未转换");
                }else if("1".equals(status)){
                    e.setStatusName("转换中");
                }else if("2".equals(status)){
                    e.setStatusName("转换成功");
                }else if("3".equals(status)){
                    e.setStatusName("转换失败");
                }
            });
            PageResult<?> pageResult = new PageResult<ShploadTask>(dt.getCurrent(), dt.getSize(), dt.getTotal(), dt.getRecords());
            return RespBean.success("获取成功", pageResult);
        } catch (Exception e) {
            return RespBean.error("无数据");
        }
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "添加ShpLoadTask")
    @PostMapping(value = "", consumes = "application/json", produces = "application/json")
    public RespBean add(@RequestBody ShploadAdd shploadAdd) {
        try {
            String shpfile = shploadAdd.getShpfile();
            QueryWrapper<ShploadTask> wapper = new QueryWrapper();
            wapper.eq("shpfile",shpfile).or().eq("name",shploadAdd.getName());
            int count = shploadTaskService.count(wapper);
            if(count>0){
                return RespBean.error("任务名称或shpfile数据源在任务中已存在，不可重复添加");
            }
            shploadAdd.setStatus("0");
            int result = shploadTaskService.add(shploadAdd);
            if (0 == result) {
                return RespBean.error("添加的数据重复");
            }
            Spatialdb spatialdb = spatialdbService.getById(shploadAdd.getDbid());
            String shpCmd = pgtool + "shp2pgsql.exe -s " + shploadAdd.getEpsg() + " -W GBK " + shploadAdd.getShpfile() +
                    " public." + shploadAdd.getName() + " | " + pgtool + "psql.exe -h " + spatialdb.getIp() + " -U " + spatialdb.getDbuser() + " -d " + spatialdb.getName() + " -p " + spatialdb.getPort();
            Map<String,Object> map = new HashMap<>();
            map.put("shpCmd",shpCmd);
            map.put("taskId",result);
            map.put("type","shp");
            rabbitTemplate.convertAndSend(RabbitMqConfig.EXCHANGE_NAME, RabbitMqConfig.BINDING_KEY_1, map);
            return RespBean.success("添加成功", result);
        } catch (Exception exp) {
            System.out.println(exp.getMessage());
            return RespBean.error("添加不成功");
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "获取指定id的ShpLoadTask")
    @GetMapping(value = "/{id}", produces = "application/json")
    public RespBean getById(@PathVariable(value = "id") Integer id) {
        try {
            ShploadGet shploadGet = shploadTaskService.getShploadTaskById(id);
            if (null == shploadGet) {
                return RespBean.error("记录不存在");
            }
            return RespBean.success("获取成功", shploadGet);
        } catch (Exception exp) {
            return RespBean.error("获取不成功");
        }
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "更新指定id对象")
    @PatchMapping(value = "/{id}", produces = "application/json")
    public RespBean update(@PathVariable(value = "id") Integer id, @RequestBody ShploadTask shploadTask) {
        try {
            shploadTask.setId(id);
            int result = shploadTaskService.updateShploadTask(shploadTask);
            if (0 == result) {
                return RespBean.error("指定更新的数据不存在");
            }
            if (-1 == result) {
                return RespBean.error("指定更新的记录与已有记录的name值重复");
            }
            return RespBean.success("更新成功", result);
        } catch (Exception exp) {
            return RespBean.error("更新不成功");
        }
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "删除指定id对象")
    @DeleteMapping(value = "/{id}", produces = "application/json")
    public RespBean delete(@PathVariable(value = "id") Integer id) {
        try {
            int result = shploadTaskService.deleteShploadTask(id);
            if (0 == result) {
                return RespBean.error("需要删除的数据不存在");
            }
            return RespBean.success("删除成功", result);
        } catch (Exception exp) {
            return RespBean.error("删除不成功");
        }
    }
}
